/**
 * 用户登录模块
 * 先需要引入login.css
 *              layui-windows-desk-logging-in  是否展示所有内容的class,如果是就展示所有
 *              layui-input-hover  判断有没有点击input框
 */
("use strict");
(function(){
  var CRC;
  layui.binder.extend({
    name: "login",
    data: function(){
      return {};
    },
    template: `
    <div class="layui-windows-desk-login" *loginflag :class = "loginflag" *required = "required">
        <div class="icon">
            <i class="layui-icon layui-icon-release"></i>
        </div>
        <div class="body">
            <div class="frame"></div>
            <div class="layui-form" expression *form = "{}" v-form = "form"  >
                <div id = "layui-form-item-username" class="layui-form-item" *hoverinput :class = "hoverinput" @click="hoverInputEvent" >
                    <div class="layui-input-display" *username >{{username}}</div>
                    <div class="layui-input-wrap">
                        <input type="text" name="username" @blur="leaveInputEvent" @focus="b.hoverinput='layui-input-hover'" @keydown="listening" :lay-verify="{{required}}" placeholder="请输入用户名" lay-reqtext="请填写用户名"  autocomplete="off" class="layui-input" lay-affix="clear">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="layui-icon layui-icon-password"></i>
                        </div>
                        <input type="password" name="password" :lay-verify="{{required}}" placeholder="密   码"
                            lay-reqtext="请填写密码" autocomplete="off" class="layui-input" @keydown="listening" lay-affix="eye">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-row">
                        <div class="layui-col-xs7">
                            <div class="layui-input-wrap">
                                <div class="layui-input-prefix">
                                    <i class="layui-icon layui-icon-vercode"></i>
                                </div>
                                <input type="text" name="captcha" :lay-verify="{{required}}" placeholder="验证码"
                                    lay-reqtext="请填写验证码" autocomplete="off" class="layui-input" @keydown="listening" lay-affix="clear">
                            </div>
                        </div>
                        <div class="layui-col-xs5">
                            <div style="margin-left: 10px;" @click = "getCaptcha">
                                <img *captcha :src="{{captcha}}" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <button style="width: 100%;" class="layui-btn" type="button" lay-submit lay-filter="WdBridgeAdd-submit" @click="submit" title="登录">登录</button>
                </div>
            </div>
        </div>
    </div>`,
    computeds: {
      isLogin(){
        return !this.loginflag == 'layui-windows-desk-logging-in';
      }
    },
    methods: {
      init(){
        // 初始化用户名称
        let users = layui.sessionData(LAYUI_USER_FIELD);
        if(users.name){
          let self = this;
          setTimeout(function(){
            self.form.username = users.name;
          });
        }else{
          let self = this;
          setTimeout(function(){
            self.hoverinput='layui-input-hover';
          });
        }
        // 刷新验证码
        this.getCaptcha();
      },
      listening(e){
        if(e.keyCode == 13) this.submit();
      },
      hoverInputEvent(){
        // 填写用户名称
        this.hoverinput='layui-input-hover';
        // 输入框获得焦点
        $(this.parent).find('[name="username"]').focus();
      },
      leaveInputEvent(){
        if(this.form.username)
          this.hoverinput='';
      },
      submit(){
        // 点击提交表单的按钮
        let self = this;
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(LAYER_PUBLIC_KEY);
        var password = encrypt.encrypt(self.form.password);
        $.ajax({
          url: LAYER_BASE_URL + '/index/login',
          data: {
              username: self.form.username,
              password: password,
              vercode: self.form.captcha,
              crc: CRC,
          },
          type: 'post',
          dataType: 'json',
          success: function (res) {
            if(res.code === 200){
              if (res.data != null) {
                layui.layer.msg(res.msg, {icon: 6});
                // 缓存用户信息
                layui.sessionData(LAYUI_USER_FIELD, {
                    key: 'data',
                    value: res.data
                });
                layui.sessionData(LAYUI_USER_FIELD, {
                  key: 'name',
                  value: res.data ? res.data.username : ''
                });
                self.required = '';
                self.form.password = '';
                self.form.captcha = '';
                self.required = 'required';
                self.loginflag = '';
                layui.windows.instance().$data.menusVisable = 'true';
              }else{
                self.getCaptcha();
                layui.layer.msg(res.msg, {icon: 2});
              }
            }else{
              self.getCaptcha();
              layui.layer.msg(res.msg, {icon: 2});
            }
          },
          error: function(){
            self.getCaptcha();
            layui.layer.msg('服务异常,请稍后再试!', {icon: 2});
          },
        });
      },
      touch(){
        // 测试是否是登录状态
        $.ajax({
          url: LAYER_BASE_URL + '/index/get',
          data: {username: this.form.username},
          type: 'post',
          dataType: 'json',
        });
      },
      logout(){
        // 退出登录
        let self = this;
        layui.layer.confirm('确认退出？',{skin: 'layui-layer-windows'}, function (index) {
          let users = layui.sessionData(LAYUI_USER_FIELD);
          if (users) {
              $.ajax({
                  url: LAYER_BASE_URL + '/index/logout',
                  type: 'post',
                  dataType: 'json',
              })
          }
          self.afterLogout();
          layui.layer.close(index);
        });
      },
      afterLogout(){
        // 退出登录后移除session信息，打开登录窗口
        layui.sessionData(LAYUI_USER_FIELD, {
          key: 'data',
          remove: true,
        });
        // 关闭弹层
        layui.windows.instance().closeAll();
        // 关闭菜单
        layui.windows.instance().$data.menusVisable = 'false';
        this.loginflag = '';
        this.loginflag = 'layui-windows-desk-logging-in';
        // 刷新验证码
        this.getCaptcha();
        this.required = '';
        this.form.password = '';
        this.form.captcha = '';
        this.required = 'required';
        layui.layer.msg('请重新登录!',{icon: 6});
      },
      getCaptcha(){
        // 更新验证码
        let self = this;
        $.ajax({
          url: LAYER_BASE_URL + '/index/vercode',
          data: {crc: CRC},
          type: 'post',
          dataType: 'json',
          success: function (res) {
            if(res.code == 200)
              self.captcha = 'data:image/png;base64,' + res.data.image;
          }
        });
      },
    },
    mounted(){
      this.$watch('form.username',{
        immediate: true,
        deep: false,
        handler(value) {
          this.username = value;
          //if(!value) this.hoverInputEvent();
        },
      });
      this.init();
    },
  });
  var VM;
  const LOGIN_ID = "layui-login";
  layui.enableLogin = function(crc){
    if(crc) CRC = crc;
    if (VM) return VM;
    $('body').append(
      $(`
      <div id = "${LOGIN_ID}">
        <login></login>
      </div>
    `)
    );
    VM = layui.binder({
      el: "#" + LOGIN_ID,
      components: {
        login: "login",
      },
      beforeDestroy() {
        $body.find("#" + LOGIN_ID).remove();
      },
    });
    return VM;
  };
})();
